<template>
  <div>
    <!-- 1-面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 2-卡片试图 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true">
            添加角色
          </el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-row>
        <el-table :data="rolelist" border stripe row-key="id">
          <!-- 展开列 -->
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row
                :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
                v-for="(item1, i1) in scope.row.children"
                :key="item1.id"
              >
                <!-- 一级 -->
                <el-col :span="5">
                  <el-tag
                    closable
                    @close="removeRightaByID(scope.row, item1.id)"
                  >
                    {{ item1.authName }}
                  </el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 二级和三级权限 -->
                <el-col :span="19">
                  <!-- 通过循环嵌套渲染二级权限 -->
                  <el-row
                    v-for="(item2, i2) in item1.children"
                    :key="item2.id"
                    :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  >
                    <!-- 二级 -->
                    <el-col :span="6">
                      <el-tag
                        type="success"
                        closable
                        @close="removeRightaByID(scope.row, item2.id)"
                      >
                        {{ item2.authName }}
                      </el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <!-- 三级 -->
                    <el-col :span="18">
                      <el-tag
                        type="warning"
                        v-for="item3 in item2.children"
                        :key="item3.id"
                        closable
                        @close="removeRightaByID(scope.row, item3.id)"
                      >
                        {{ item3.authName }}
                      </el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <!-- 索引列 -->
          <el-table-column type="index"></el-table-column>
          <el-table-column label="角色名称" prop="roleName"></el-table-column>
          <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
          <el-table-column label="操作" width="300px">
            <template slot-scope="scope">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showEditDialog(scope.row.id)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeUserByid(scope.row.id)"
              >
                删除
              </el-button>
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showSetRihtDialog(scope.row)"
              >
                分配权限
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
    </el-card>

    <!-- 3-添加角色的对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 表单区域  -->
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="70px"
      >
        <!-- 用户名 -->
        <el-form-item label="角色名称" prop="roleName" label-width="80px">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="角色描述" prop="roleDesc" label-width="80px">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false"> 取 消 </el-button>
        <el-button type="primary" @click="addUser"> 确 定 </el-button>
      </span>
    </el-dialog>

    <!-- 4-修改角色对话框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 表单区域  -->
      <el-form
        ref="editFromRef"
        :model="editFrom"
        :rules="addFormRules"
        label-width="70px"
      >
        <!-- 用户名 -->
        <el-form-item label="角色名称" prop="roleName" label-width="80px">
          <el-input v-model="editFrom.roleName"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="角色描述" prop="roleDesc" label-width="80px">
          <el-input v-model="editFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false"> 取 消 </el-button>
        <el-button type="primary" @click="editUserInfo"> 确 定 </el-button>
      </span>
    </el-dialog>

    <!-- 5.分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <!-- 树形结构 -->
      <el-tree
        ref="treeRef"
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
      ></el-tree>
      <!-- 底部确认取消 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false"> 取 消 </el-button>
        <el-button type="primary" @click="allotRighrs"> 确 定 </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 所有角色列表数据
      rolelist: [],
      //   添加用户表单的数据
      addForm: {
        roleName: '',
        roleDesc: '',
      },
      //   定义添加用户对话框显示和隐藏
      addDialogVisible: false,
      //   添加——用户表单数据验证规则
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名长度在3~10个字符',
            trigger: 'blur',
          },
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 4,
            max: 10,
            message: '用户名长度4~10个字符',
            trigger: 'blur',
          },
        ],
      },
      // 控制修改表单的显示和隐藏
      editDialogVisible: false,
      //   获取修改用户列表的数据
      editFrom: {},
      // 控制分配权限的对话框显示和隐藏
      setRightDialogVisible: false,
      // 所有权限列表的数据
      rightsList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        // 显示的值
        label: 'authName',
        // 父子节点绑定的节点
        children: 'children',
      },
      // 默认选中的节点的ID值
      defKeys: [],
      // 当前即将分配权限的id
      roleid: '',
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 获取所有角色列表
    async getRoleList() {
      const { data: result } = await this.$http.get('roles')
      if (result.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolelist = result.data
    },
    // 添加用户的关闭清空事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        // console.log(valid)
        if (!valid) return
        // 正确发起请求
        const { data: result } = await this.$http.post('roles', this.addForm)
        if (result.meta.status !== 201) {
          this.$message.error('创建角色失败')
        }
        this.$message.success('创建角色成功')
        this.addDialogVisible = false
        this.getRoleList()
      })
    },
    // 监听——修改用户的关闭事件
    editDialogClosed() {
      this.$refs.editFromRef.resetFields()
    },
    // 点击修改，显示修改对话框
    async showEditDialog(id) {
      const { data: result } = await this.$http.get('roles/' + id)
      if (result.meta.status !== 200) {
        return this.$message.error('查询角色列表失败')
      }
      this.editFrom = result.data
      // console.log(this.editFrom)
      this.editDialogVisible = true
    },
    // 点击修改对话框的确定，并提交，进行预验证
    editUserInfo() {
      this.$refs.editFromRef.validate(async (valid) => {
        // console.log(valid)
        if (!valid) return
        const { data: result } = await this.$http.put(
          'roles/' + this.editFrom.roleId,
          {
            roleName: this.editFrom.roleName,
            roleDesc: this.editFrom.roleDesc,
          }
        )
        if (result.meta.status !== 200) {
          return this.$message.error('更新角色信息失败')
        }
        // 若更新角色成功
        this.editDialogVisible = false
        // 刷新数据列表
        this.getRoleList()
        this.$message.success('更新角色信息成功')
      })
    },
    // 点击删除，弹出对话框
    async removeUserByid(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => {
        return err
      })
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除')
      }
      const { data: result } = await this.$http.delete('roles/' + id)
      if (result.meta.status !== 200) {
        return this.$message.error('删除角色失败')
      }
      this.$message.success('删除用户成功')
      this.getRoleList()
    },
    // 点击×，根据ID删除对应的权限
    async removeRightaByID(role, rightsID) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => {
        return err
      })
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: result } = await this.$http.delete(
        `roles/${role.id}/rights/${rightsID}`
      )
      if (result.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      role.children = result.data
      // 不适用getRoleList会刷新页面
      // this.getRoleList()
    },
    // 点击分配权限。展示对话框
    async showSetRihtDialog(role) {
      // 获取当前的id
      this.roleid = role.id
      // 获取所有权限的数据
      const { data: result } = await this.$http.get('rights/tree')
      if (result.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      // 获取所有权限列表数据保存到rightsList
      this.rightsList = result.data
      // console.log(this.rightsList)
      // console.log(role)
      // 递归获取3级节点的ID
      this.getLeafKeys(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    // 通过递归的方式，获取角色下3级节点权限的ID
    getLeafKeys(node, arr) {
      // 若当前节点不包含children属性，则为3级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr)
      })
    },
    // 监听分配权限的关闭事件
    setRightDialogClosed() {
      this.defKeys = []
    },
    // 点击确认，为角色分配权限
    async allotRighrs() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]
      // console.log(keys)
      const IDstr = keys.join(',')
      const { data: result } = await this.$http.post(
        `roles/${this.roleid}/rights`,
        { rids: IDstr }
      )
      if (result.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRoleList()
      this.setRightDialogVisible = false
    },
  },
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>